package com.content.controller;

import java.awt.Window;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Array;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.Map.Entry;
import java.util.UUID;

import javax.annotation.Resource;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonNumber;
import javax.json.JsonObject;
import javax.json.JsonString;
import javax.json.JsonValue;
import javax.json.JsonValue.ValueType;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;

import org.apache.log4j.Logger;
import org.aspectj.weaver.ast.And;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.content.pojo.Article;
import com.content.pojo.ArticleClass;
import com.content.pojo.ArticleClassExample;
import com.content.pojo.BelongtoKey;
import com.content.pojo.CollectKey;
import com.content.pojo.Comment;
import com.content.pojo.Focus;
import com.content.pojo.User;
import com.content.service.ArticleClassService;
import com.content.service.ArticleService;
import com.content.service.UserService;
import com.content.util.BeanFactory;
import com.content.util.HtmlToCodeUtil;
import com.content.util.IntervalUtil;
import com.content.util.State;
import com.content.util.getImageName;



@Controller
@RequestMapping("/User")
public class userController {
	//HttpSession session;
	//private static Logger logger = Logger.getLogger(userController.class);
	@Autowired
	private UserService userService;
	
	@Autowired
	private ArticleService aService;
	
	@Autowired
	private ArticleClassService aClassService;
	/*
	 * 这个是测试control**/
	@RequestMapping("/findAllUser")
	public String findAllUser(HttpServletRequest request){
		List<User> listUser =  userService.findAllUser();
		request.setAttribute("listUser", listUser);
		return "allUser";
	}
	
	/*
	 * 这个是测试control**/
	@RequestMapping("/index")
	public String findIndex(){
		return "index/index";
	}
	/*
	 * 这个是测试control**/
	@RequestMapping("/template/nav")
	public String findNav(){
		return "template/nav";
	}
	/*
	 * 这个是测试control**/
	@RequestMapping("/template/indexTpl")
	public String findIndexTempl(){
		return "template/indexTpl";
	}

	/*
	 * 这个是测试control**/
	@RequestMapping("/template/writeDown")
	public String findWD(){
		return "template/writeDown";
	}
	
	@RequestMapping("/template/articleDetail")
	public String findAD(){
		return "template/articleDetail";
	}
	
	/*
	 * 这个是测试control**/
	@RequestMapping("/template/loginTpl")
	public String findLoginTpl(){
		return "template/loginTpl";
	}
	
	/*
	 * 这个是测试control**/
	@RequestMapping("/template/registerTpl")
	public String findRegisterTpl(){
		return "template/registerTpl";
	}
	

	/*
	 * 这个是测试control**/
	@RequestMapping("/template/settingTpl")
	public String findSettingTpl(){
		return "template/settingTpl";
	}
	
	/*
	 * 这个是测试control**/
	@RequestMapping("/template/userIndex")
	public String findUserInex(){
		return "template/userIndex";
	}
	
	/*
	 * 这个是测试control**/
	@RequestMapping("/template/selectClassTpl")
	public String findSelectClassTpl(){
		return "template/selectClassTpl";
	}
	/*
	 * 这个是测试control**/
	@RequestMapping("/template/classInfoTpl")
	public String findClassInfoTpl(){
		return "template/classInfoTpl";
	}
	
	
	/*
	 * 这个是测试control**/
	@RequestMapping("/template/indexList")
	public String findIndexList(){
		return "template/indexList";
	}
	
	/*
	 * 这个是测试control**/
	@RequestMapping("/template/commentTpl")
	public String findCommentTpl(){
		return "template/commentTpl";
	}
	
	/*
	 * 这个是测试control**/
	@RequestMapping("/template/timelineTpl")
	public String findTimelineTpl(){
		return "template/timelineTpl";
	}
	
	/**
	 * @describe: 登录验证
	 * @param user: 自动注入值*/
	@RequestMapping(value="userlogin",method = RequestMethod.POST) 
    public  void loginl(User user,HttpServletRequest request,HttpServletResponse response) throws IOException{
		
		List<User> userlist =userService.getUser(user);
		PrintWriter out = response.getWriter();
		JSONObject object = new JSONObject();
		if(userlist.size()==0){//登录失败
//			out.print(2);
			object.put("status", 2);
		} else if(userlist.size() == 1){//登录成功
		//	String[] str = user.getId().split("@");
			if(userlist.get(0).getType() == 0){
				userService.updateUserLoginTime(user);
//				out.print(userlist.get(0));
//				out.print(-1);
				object.put("user", userlist.get(0));
				object.put("status", -1);
			}else{
				userService.updateUserLoginTime(user);
				HttpSession session = request.getSession();
				session.setAttribute("id", request.getParameter("id"));
//				out.print(userlist.get(0));
//			    out.print(1);
				object.put("user", userlist.get(0));
				object.put("status", 1);
			}
		}
		else{
//			out.print(0);
			object.put("status", 0);
		}
		
		out.print(object);
	}
	/**
	 * @describe: 注册验证
	 * @param user: 自动注入值*/
	@RequestMapping(value="loginCheck",method = RequestMethod.POST) 
	public  void register(User user, HttpServletRequest request,HttpServletResponse response) throws IOException{
		System.out.println(user.getUsername());
		PrintWriter out = response.getWriter();
		user.setType(1);
		user.setArticleNum(0);
		user.setAge(0);
		
		if(userService.findUserName(user.getUsername()) != 0){
			out.print(-1);	
			}
		else if(userService.findUserById(user.getId()) != 0){
			out.print(2);
		}
		else{
			userService.addUser(user);
			out.print(1);
		}
		
	}
	
	/*
	 * 查看个人信息**/
	@RequestMapping(value="settingInfo",method = RequestMethod.GET) 
	public void SettingInfo(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException{
		
		PrintWriter out = response.getWriter();
		HttpSession session = request.getSession();
		//System.out.println((String) session.getAttribute("id"));
		
		if((String) session.getAttribute("id") != null && (String) session.getAttribute("id") != "")
		{
			String userid = (String) session.getAttribute("id");

			User realUser = userService.getUserInfo(userid);
			
			Object  jsonObject = JSON.toJSON(realUser);
			request.setAttribute("id", realUser.getId());
			out.print(jsonObject);
			
		}else{
//			20160227ny:8080/ContentManagerSystem/User/settingInfo
//			20160227ny:8080/User/userlogin
//			response.sendRedirect("index#/login");
//			request.getRequestDispatcher("index").forward(request, response);
			Map<String, Object> statusMap = new HashMap<String, Object>();
			statusMap.put("noLogin", 1);
			out.print(new JSONObject(statusMap));
		}
		
		
		
	}
	
	/*
	 * 更新个人信息(还没有实现)**/
	@RequestMapping(value="updateInfo",method = RequestMethod.POST) 
	public void updateInfo(@RequestParam("iconFile") MultipartFile icon, String username, Short gender, int age,String name, HttpServletRequest request,HttpServletResponse response) throws IOException{
		PrintWriter out = response.getWriter();
		HttpSession session = request.getSession();
		try{
			String userid = (String) session.getAttribute("id");
			
			String path = request.getSession().getServletContext().getRealPath("WEB-INF/upload"); 
			String oldName = icon.getOriginalFilename();
			String newName = getImageName.imageName();
			newName = newName + oldName.substring(oldName.lastIndexOf("."));
			File file = null;
			icon.transferTo(file = new File(path, newName));         
			System.out.println(icon);
			User newUser = new User();
			newUser.setId(userid);
			newUser.setUsername(username);
			newUser .setGender(gender);
			newUser.setAge(age);
			newUser.setName(name);
			newUser.setIcon("../upload/" + newName);
			
		    userService.updateUserInfo(newUser);
//		  
		    out.print(1);
	    }catch(Exception e){
	    	e.printStackTrace();
	    }
	}
	

	/*
	 * 修改密码**/
	@RequestMapping(value="modifyPassWord",method = RequestMethod.POST) 
	public void modifyPassWord(String password, String newPassword, HttpServletRequest request,HttpServletResponse response) throws IOException{
		PrintWriter out = response.getWriter();
		HttpSession session = request.getSession();
		String userid = (String) session.getAttribute("id");
		User newUser = new User();
		newUser.setId(userid);
		newUser.setPassword(newPassword);
		
		String word = userService.getUserInfo(userid).getPassword();
		System.out.println(word);
		System.out.println(newPassword);
		
		if(word.equals(password)){
			
			userService.modifyPassWord(newUser);
			System.out.println("success!");
			out.print(1);
		}
	   
	}
	
	/*
	 * 退出登录(不成功，session还是存在)
	 * **/
	@RequestMapping(value="loginout",method = RequestMethod.POST) 
	public void loginOut(HttpServletRequest request,HttpServletResponse response) throws IOException{
		PrintWriter out = response.getWriter(); 
		System.out.println("清除session");
		HttpSession session = request.getSession();
		Enumeration<String> em = request.getSession().getAttributeNames();
//        System.out.println(em.nextElement());
		while(em.hasMoreElements()){ 
			String sessionName= em.nextElement(); 
		    System.out.println("存在的session有："+sessionName); 
		    session.removeAttribute(sessionName);
		    }
		System.out.println("success!");
		session.invalidate();
		out.print(1);


		
	}
//	
//	 @RequestMapping("loginout")
//	    public String execute(HttpSession session){
//	        session.invalidate();
//	        return "showArticle";
//	    }
	/*
	 * 展示文章条目
	 * **/
	@RequestMapping(value="showArticle",method = RequestMethod.GET) 
	public void showArticle( HttpServletRequest request,HttpServletResponse response) throws IOException{
		PrintWriter out = response.getWriter(); 
		List<Article> aList = aService.showArticle();
		
        JSONArray array = new JSONArray();
		
		for (Article article : aList){
			article.setCreatTime(new IntervalUtil().getInterval(article.getCreatTime()));
			System.out.println(article.getCreatTime());
			array.add(JSON.toJSON(article));
		}
		
		//System.out.println(aList.get(0).getTitle());
		out.print(array);
	}
	
	/*发布文章**/
	@RequestMapping(value="createArticle",method=RequestMethod.POST)
	public void createArticle(String title, String isvisible, String type,String content,HttpServletRequest request, HttpServletResponse response)
	throws IOException{
		HttpSession session = request.getSession();
		PrintWriter out = response.getWriter();
		String userId = (String) session.getAttribute("id");
//		if((String) session.getAttribute("id") != null && (String) session.getAttribute("id") != "")
//		{
//		System.out.println((String) session.getAttribute("id"));
	    UUID uuid = UUID.randomUUID();
	    String articleId = uuid.toString();
	    Date createTimeDate = new Date();
	    SimpleDateFormat str = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    String time = str.format(createTimeDate);
	    String htmlString= HtmlToCodeUtil.htmlToCode(content);
//	    System.out.println(htmlString);
	    
	    Article article = new Article();
	    article.setArticleId(articleId);
	    article.setUseId(userId);
	    article.setTitle(title);
	    article.setLooknum(0);
	    article.setCreatTime(time);
	    article.setContent(htmlString);
	    article.setUpdateTime(time);
	    article.setCollectnum(0);
	    
//	    System.out.println(title);
	    
		if(isvisible.equals("0")){
			article.setIsvisible(0);
			aService.createArticle(article);
		}
		if(isvisible.equals("1")){
			out.print(articleId);
		    article.setIsvisible(1);
		    User user = userService.getUserInfo(userId);
		    System.out.println(user.getId()+"" + user.getName()+":"+user.getArticleNum()
		    		+ user.getPassword() + user.getGender()+ user.getAge());
//		   System.out.println(user.getArticleNum());
		    user.setArticleNum(user.getArticleNum()+1);
		    System.out.println(user.getArticleNum());
		    article.setUser(user);
//
		    userService.updateUserAticleNum(user); 
		    aService.createArticle(article);
		//    System.out.println(request.getParameter("type"));
		    
		    BelongtoKey belongtoKey1 = new BelongtoKey();
		    belongtoKey1.setArticleId(articleId);
		    belongtoKey1.setClassId(type);
		    Date date =  new Date();
		    String applyTime = str.format(date);
		    belongtoKey1.setApplyTime(applyTime);
		    belongtoKey1.setIsBoolean(2);
		    userService.addArticleMapToClass(belongtoKey1);
		}

	}
	
	/*获取个人文章分类
	 * **/
	@RequestMapping(value="userClass", method= RequestMethod.POST)
	public void getUserClass(HttpServletRequest request,HttpServletResponse response)
	throws IOException{
		PrintWriter out = response.getWriter(); 
		HttpSession session = request.getSession();
		String id = (String) session.getAttribute("id");
		List<ArticleClass> alist = userService.getUserClass(id);
		
		JSONArray array = new JSONArray();
		for (ArticleClass articleClass : alist){
			array.add(JSON.toJSON(articleClass));
		}
		
		out.print(array);
	}
	/*
	 * 删除个人文章分类
	 * **/
	@RequestMapping(value="deleteUserClass",method=RequestMethod.POST)
	public void deleteUserClass(HttpServletRequest request,HttpServletResponse response)
	throws IOException{
		PrintWriter out = response.getWriter();
		HttpSession session = request.getSession();
		String user_id = (String) session.getAttribute("id");
		userService.deleteUserClass(user_id);
	}
	/*
	 * 获取个人文章
	 * **/
	@RequestMapping(value="getUserArticle",method=RequestMethod.POST)
	public void getUserArticle(String userId,HttpServletResponse response,HttpServletRequest request)
	throws IOException{
		PrintWriter out = response.getWriter();
		HttpSession session = request.getSession();
	//	String user_id = (String) session.getAttribute("id");
		String userID = request.getParameter("userId");
		System.out.println(userID);
		List<Article> alList = userService.getUserArticle(userID);
		
		System.out.println(alList.get(0).getUseId());
		System.out.println(alList.get(0).getUser().getUsername());
		System.out.println(alList.get(0).getTitle());
	    System.out.println(alList.size());
	    
	    JSONArray array = new JSONArray();
		for (Article article : alList){
		//	article.setCreatTime(new IntervalUtil().getInterval(article.getCreatTime()));
			array.add(JSON.toJSON(article));
		}
		
		out.print(array);
	}
	
	/*
	 * 删除个人文章
	 * **/
	@RequestMapping(value="deleteUserArticle",method=RequestMethod.POST)
	public void deleteUserArticle(HttpServletRequest request, HttpServletResponse response)
	throws IOException{
		PrintWriter out = response.getWriter();
		HttpSession session = request.getSession();
		String user_id = (String) session.getAttribute("id");
		userService.deleteUserArticle(user_id);
	}
	
	/*
	 * 删除评论
	 * **/
	@RequestMapping(value="deleteComment", method= RequestMethod.POST)
	public void deleteComment(Comment comment,HttpServletRequest request , HttpServletResponse response)
	throws IOException{
		PrintWriter out = response.getWriter();
		HttpSession session = request.getSession();
		String user1_id = (String) session.getAttribute("id");
		userService.deleteComment(comment);
	}
	
	/*显示评论(还要修改)
	 * **/
	@RequestMapping(value="showComment", method= RequestMethod.POST)
	public void ShowArticle(String articleId, HttpServletResponse response, HttpServletRequest request)
	throws IOException{
		PrintWriter out = response.getWriter();
		HttpSession session = request.getSession();
		String user1_id = (String) session.getAttribute("id");
		userService.showComment(articleId);
	}
	
	/*用户增加文章分类**/
	@RequestMapping(value="addUserClass", method= RequestMethod.POST)
	public void addUserClass(HttpServletRequest request,HttpServletResponse response)
	throws IOException{
		PrintWriter out = response.getWriter();
		HttpSession session = request.getSession();
		String user1_id = (String) session.getAttribute("id");
		String title = request.getParameter("typeName");
//		insert into article_class(class_id,title,discribe,type, createTime,user_id,parent_id) values(#{class_Id},#{title},#{title},#{type},#{createTime},
//		        #{user_id},#{parent_id})
		ArticleClass articleClass = new ArticleClass();
		UUID uuid = UUID.randomUUID();
		String class_idString= uuid.toString();
		Date tDate = new Date();
		SimpleDateFormat sFormat =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    String time = sFormat.format(tDate);
	    articleClass.setClassId(class_idString);
	    articleClass.setTitle(title);
	    articleClass.setDiscribe(null);
	    articleClass.setType(1);
	    articleClass.setCreateTime(time);
	    articleClass.setUser_id(user1_id);
	    articleClass.setParent_id("0");
	    userService.addUserClass(articleClass);
	}
	
	/*显示文章详情**/
	@RequestMapping(value="getArticle", method= RequestMethod.POST)
	public void articleDetail(String articleId, HttpServletRequest request, HttpServletResponse response)
	throws IOException{
		PrintWriter out = response.getWriter();
		Article article = aService.articleDetail(articleId);
		System.out.println(articleId);
		article.setLooknum(article.getLooknum()+1);
		aService.updateLookNum(article);
		article.setContent(HtmlToCodeUtil.codeToHtml(article.getContent()));
		Object object = JSONObject.toJSON(article);
		out.print(object);
	}
	

	/*搜索(还要修改)
	 * **/
	@RequestMapping(value="searchArticle", method= RequestMethod.POST)
	public void searchArticle(HttpServletResponse response, HttpServletRequest request)
	throws IOException{
		PrintWriter out = response.getWriter();
		HttpSession session = request.getSession();
		String keyWord = request.getParameter("word");
		System.out.println(keyWord);
		List<Article> aList = userService.searchArticleByWord(keyWord);
		JSONArray array = new JSONArray();
		for (Article article : aList){
			array.add(JSON.toJSON(article));
		}
		out.print(array);
	}
	
	/*上传图片**/
	@RequestMapping(value="uploadImage", method= RequestMethod.POST)
	 public void uploadImage(@RequestParam("iconFile") MultipartFile icon, HttpServletRequest request) {
	     System.out.println(request.getParameter("text"));
//		 MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest)request;
			
//		 MultipartFile uploadFile = mRequest.getFile("icon");
		 String path = request.getSession().getServletContext().getRealPath("WEB-INF/upload"); 
	     String oldName = icon.getOriginalFilename();
	     String newName = getImageName.imageName();
	     newName = newName + oldName.substring(oldName.lastIndexOf("."));
          try {
	            icon.transferTo(new File(path, newName));
	        } catch (Exception e) {
	        	e.printStackTrace();
	        }

          //之后可以将这个路径保存到数据库中
         
	    }
	
	
	/*按热度排序**/
	@RequestMapping(value="sortByHot", method= RequestMethod.POST)
	public void sortByHot(HttpServletRequest request, HttpServletResponse response)
	throws IOException{
		PrintWriter out = response.getWriter();
		List<Article> aList = aService.sortByHot();
		JSONArray array = new JSONArray();
		for (Article article : aList){
			array.add(JSON.toJSON(article));
		}
		out.print(array);
	}
	
	/*按更新时间排序**/
	@RequestMapping(value="sortByTime", method= RequestMethod.POST)
	public void sortByTime(HttpServletRequest request, HttpServletResponse response)
	throws IOException{
		PrintWriter out = response.getWriter();
		List<Article> aList = aService.sortByTime();
		JSONArray array = new JSONArray();
		for (Article article : aList){
			article.setCreatTime(new IntervalUtil().getInterval(article.getCreatTime()));
			array.add(JSON.toJSON(article));
		}
		out.print(array);
	}
	
	/*显示所有专题**/
	@RequestMapping(value="queryClass", method= RequestMethod.GET)
	public void queryClass(HttpServletRequest request, HttpServletResponse response)
	throws IOException{
		PrintWriter out = response.getWriter();
		List<ArticleClassExample> aClasses = aClassService.getAllClasses();
		
		System.out.println(aClasses.size());
		JSONArray array = new JSONArray();
		for (ArticleClassExample articleClass : aClasses){
			array.add(JSON.toJSON(articleClass));
		}
		out.print(array);
	}
	
	/*投稿**/
	@RequestMapping(value="publish", method= RequestMethod.POST)
	public void publish(String articleId, String classId, HttpServletRequest request, HttpServletResponse response)
	throws IOException{
		 PrintWriter out = response.getWriter();
		 BelongtoKey belongtoKey = new BelongtoKey();
		 belongtoKey.setArticleId(articleId);
	
		 System.out.println(classId);
		 String stringId = classId.substring(1, classId.length()-1);
		 String[] drop = stringId.split("\"");
//		 for(String s: drop)
//			 System.out.println(s);
		 String realIdString = drop[1];
		 System.out.println(realIdString);
		 belongtoKey.setClassId(realIdString);
		 Date date =  new Date();
		 SimpleDateFormat str = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		 String applyTime = str.format(date);
		 belongtoKey.setApplyTime(applyTime);
		 belongtoKey.setIsBoolean(0);
		 userService.addArticleMapToClass(belongtoKey);
		 out.print(1);
	}
	
	
//	/*
//	 * 通过个人分类获取个人文章
//	 * **/
//	@RequestMapping(value="getarticleInClass",method=RequestMethod.POST)
//	public void getarticleInClass(String userId,String class_Id,HttpServletResponse response,HttpServletRequest request)
//	throws IOException{
//		PrintWriter out = response.getWriter();
//		HttpSession session = request.getSession();
//
//		Article arti = new Article();
//		arti.getUser().setId(userId);
////	    arti.getArticleClass().get(0).setClassId(class_Id);
//		List<Article> alList = userService.getarticleInClass(arti);
//		
//		System.out.println(alList.get(0).getUseId());
//		System.out.println(alList.get(0).getUser().getUsername());
//		System.out.println(alList.get(0).getTitle());
//	    System.out.println(alList.size());
//	    
//	    JSONArray array = new JSONArray();
//		for (Article article : alList){
//			article.setCreatTime(new IntervalUtil().getInterval(article.getCreatTime()));
//			array.add(JSON.toJSON(article));
//		}
//		
//		out.print(array);
//	}
	
	/*获取系统分类**/
	@RequestMapping(value="queryAllClass", method= RequestMethod.GET)
	public void queryAllClass(HttpServletRequest request, HttpServletResponse response)
	throws IOException{
	
	List<ArticleClassExample> aList = aClassService.getAllClasses();
		
		JSONArray array = new JSONArray();
		
		for (ArticleClassExample articleClassExample : aList){
			array.add(JSON.toJSON(articleClassExample));
		}
		
		//System.out.println(aList.get(0).getTitle());
		PrintWriter out = response.getWriter();
		out.print(array);
	}
	
	
	/*根据分类获取文章**/
	@RequestMapping(value="getArticleInClass", method= RequestMethod.POST)
	public void getArticleInClass(String class_Id, HttpServletRequest request, HttpServletResponse response)
	throws IOException{
	  
        List<Article> aList = userService.getArticleInClass(class_Id);
		
		JSONArray array = new JSONArray();
		
		for (Article article : aList){
			array.add(JSON.toJSON(article));
		}
		
		//System.out.println(aList.get(0).getTitle());
		PrintWriter out = response.getWriter();
		out.print(array);
	}

	/*获取系统分类**/
	@RequestMapping(value="queryClassInfo", method= RequestMethod.POST)
	public void queryClassInfo(String class_Id, HttpServletRequest request, HttpServletResponse response)
	throws IOException{
	
	    ArticleClassExample aList = userService.queryClassInfo(class_Id);
		
//		JSONArray array = new JSONArray();
//		
//		for (ArticleClassExample articleClassExample : aList){
//			array.add(JSON.toJSON(articleClassExample));
//		}
		Object jsoObject = JSONObject.toJSON(aList);
		//System.out.println(aList.get(0).getTitle());
		PrintWriter out = response.getWriter();
		out.print(jsoObject);
	}
	
	/*用户收藏**/
	@RequestMapping(value="addCollection", method= RequestMethod.POST)
	public void addCollection(String articleId, String collectState, HttpServletRequest request, HttpServletResponse response)
	throws IOException{
		HttpSession session = request.getSession();
		String user_id = (String) session.getAttribute("id");
		PrintWriter out = response.getWriter();
        CollectKey collectKey = new CollectKey();
        collectKey.setArticleId(articleId);
        collectKey.setUseId(user_id);
        if(collectState.equals("true")){
        	userService.addCollection(collectKey);
        	out.print(1);
        }
        if(collectState.equals("false")){
        	userService.deleteCollection(collectKey);
        	out.print(-1);
        }
        
		
	
		
	}
	
	/*添加用户关注**/
	@RequestMapping(value="focusOn", method= RequestMethod.POST)
	public void focusOn(String userId2, String focusState, HttpServletRequest request, HttpServletResponse response)
	throws IOException{
		HttpSession session = request.getSession();
		String user_id = (String) session.getAttribute("id");
		PrintWriter out = response.getWriter();
	//	out.print(1);
		Focus focus = new Focus();
		UUID uuid = UUID.randomUUID();
		String focusIdString = uuid.toString();
		focus.setFocusId(focusIdString);
		focus.setUseId(user_id);
		focus.setUseId2(userId2);
		
		if(focusState.equals("true")){
        	userService.addFocus(focus);
        	out.print(1);
        }
        if(focusState.equals("false")){
        	userService.deleteFocus(focus);
        	out.print(-1);
        }
		
	}
	
	/*加载评论*/
	@RequestMapping(value="getCommentWithArticle", method= RequestMethod.POST)
	public void getCommentWithArticle(String articleId, HttpServletRequest request, HttpServletResponse response)
	throws IOException{
		List<Comment> comments = userService.getCommentsByArticle(articleId);
		
        JSONArray  array= new JSONArray();
		
		for (Comment c : comments){
			array.add(JSON.toJSON(c));
		}
		PrintWriter out = response.getWriter();
		out.print(array);
	}
	
	/*发表评论*/
	@RequestMapping(value="replyComment", method= RequestMethod.POST)
	public void replyComment(String articleId, String content, String parentId, HttpServletRequest request, HttpServletResponse response)
	throws IOException{
		Comment comment = new Comment();
		UUID uuid = UUID.randomUUID();
		String comment_id=uuid.toString();
		comment.setCommentId(comment_id);
		comment.setArticleId(articleId);
		comment.setIsDisplay(1);
		comment.setParentId(parentId);
		comment.setContent(content);
		System.out.println(comment.getParentId());
		HttpSession session = request.getSession();
		String user_id = (String) session.getAttribute("id");
		comment.setUseId(user_id);
		Date date = new Date();
		SimpleDateFormat str = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    String time = str.format(date);
	    comment.setCommentTime(time);
		userService.insertComment(comment);
        User user =  userService.getUserInfo(user_id);
        comment.setUser(user);
		Object jsoObject = JSONObject.toJSON(comment);
		
		PrintWriter outPrintWriter = response.getWriter();
		outPrintWriter.print(jsoObject);
	}
	
	
	/*朋友圈*/
	@RequestMapping(value="friendCycle", method= RequestMethod.GET)
	public void friendCycle(String articleId, String content, String parentId,HttpServletRequest request, HttpServletResponse response)
	throws IOException{
		HttpSession session = request.getSession();
		String user_id = (String) session.getAttribute("id");
		List<Focus> focus = userService.findFriend(user_id);
		System.out.println(focus.size());
		
        JSONArray  array= new JSONArray();
		
		for (Focus f : focus){
		    
			array.add(JSON.toJSON(f));
		}
		PrintWriter out = response.getWriter();
		out.print(array);
	}
	
	/*朋友圈评论*/
	@RequestMapping(value="queryComment", method= RequestMethod.GET)
	public void queryComment(HttpServletRequest request, HttpServletResponse response)
	throws IOException{
		HttpSession session = request.getSession();
		String user_id = (String) session.getAttribute("id");
		List<Focus> focus = userService.showCommentInFocus(user_id);
		System.out.println(focus.size());
		
        JSONArray  array= new JSONArray();
		
		for (Focus f : focus){
			array.add(JSON.toJSON(f));
		}
		PrintWriter out = response.getWriter();
		out.print(array);
	}
}
